﻿using System;
using HtmlAgilityPack;
using System.Windows.Forms;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Drawing;
using pq;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections;
using System.Data;
using System.Collections.Generic;

namespace ImgSpider
{
    public partial class Form1 : Form
    {
        const string sUserAgent ="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        const string sContentType ="application/x-www-form-urlencoded";
        const string sRequestEncoding = "ascii";
        const string sResponseEncoding = "gb2312";
        const string proxy = "127.0.0.1:8888";
        private string refer = "https://account.178.com/index.php?to=http%3A%2F%2Fi.178.com%2F";
        private string cookie = "";
        private CookieContainer cc = new CookieContainer();
        private int userIndex = 0;
        private HttpHelper http;
        private ArrayList userList = new ArrayList();
        private DataTable dt = new DataTable();
        public Form1()
        {
            InitializeComponent();
            http = new HttpHelper();
            getVCode();
        }
        private void getVCode()
        {
            HttpItem hi=new HttpItem();
            hi.ProxyIp = proxy;
            hi.Accept = "image/webp,image/apng,image/*,*/*;q=0.8";
            hi.ContentType = "image/jpeg";
            hi.Referer = "https://account.178.com/index.php?to=http%3A%2F%2Fi.178.com%2F";
            hi.URL = "https://account.178.com/q_vcode.php?_act=gen_reg";
            HttpResult hr = http.getImage(hi);
            cookie = hr.Cookie;
            img.Image = hr.image;
        }
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (tb_url.Text.Trim().Length < 5) return;
            login();
        }
        private void login()
        {
            string data = "_act=login&print=login&to=http%3A%2F%2Fi.178.com%2F&email=" + tb_usn.Text + "&password=" + tb_pwd.Text + "&vcode=" + tb_vcode.Text + "&noexpires=31536000&_=";
            HttpItem hi = new HttpItem();
            hi.ProxyIp = proxy;
            hi.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            hi.URL = tb_url.Text;
            hi.Cookie = cookie;
            hi.Method = "POST";
            hi.Postdata = data;
            HttpResult hr = http.GetHtml(hi);
            JObject o = (JObject)JsonConvert.DeserializeObject(hr.Html);
            if (o["reason"].ToString() == "error_vcode")
            {
                MessageBox.Show("验证码错误！");
                getVCode();
                return;
            }
            string url = o["url"].ToString();
            if (hr.StatusDescription == "OK")
            {
                string[] arr = hr.Cookie.Split(',');
                string ncok = "";
                ArrayList cookieArr = new ArrayList();
                foreach (string str in arr)
                {
                    if (str.IndexOf("Max-Age") != -1) continue;
                    string[] arr2 = str.Split(';');
                    ncok += arr2[0] + ";";
                    cookieArr.Add(arr2[0]);
                }
                cc = hr.cookieContainer;
                userList.Add(cookieArr);
                userIndex = userList.Count - 1;
                changeUser();
            }
            else
            {
                tb_output.Text += "登录验证失败！";
            }
        }
        private void changeUser()
        {
            string ck = string.Join(";", (string[])(userList[userIndex] as ArrayList).ToArray(typeof(string)));
            HttpItem hi = new HttpItem();
            hi.ProxyIp = proxy;
            hi.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            hi.Method = "GET";
            hi.Cookie = ck;
            HttpResult hr = http.GetHtml(hi);
            hi.URL = "http://i.178.com/";
            hr = http.GetHtml(hi);
            if (hr.Html == "")
            {
                login();
                return;
            }
            Console.Write(hr.Html);
            string usn = hr.Html.Substring(hr.Html.IndexOf("_g_comment_vname = ") + 20, 16);
            usn = usn.Substring(0, usn.IndexOf("\""));
            tb_output.Text += "\r\n当前用户>>>>>>\r\n";
            tb_output.Text += gb2312_utf8(usn);
        }
        private void getHtml()
        {
            WebRequest request = WebRequest.Create(tb_url.Text);
            WebResponse response = (WebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.Default);
            tb_output.Text += reader.ReadToEnd();
            HtmlWeb htmlWeb = new HtmlWeb();
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(tb_output.Text);//加载HTML字符串，如果是文件可以用htmlDocument.Load方法加载
            HtmlNode htmlNode = htmlDoc.DocumentNode.SelectSingleNode("//html/body/section/div[4]/div/ul/li[12]/div/a/img");
            tb_output.Text = gb2312_utf8(htmlNode.OuterHtml);
        }
        public static string gb2312_utf8(string text)
        {
            //声明字符集   
            Encoding utf8, gb2312;
            //gb2312   
            gb2312 = Encoding.GetEncoding("gb2312");
            //utf8   
            utf8 = Encoding.GetEncoding("utf-8");
            byte[] gb;
            gb = gb2312.GetBytes(text);
            gb = Encoding.Convert(gb2312, utf8, gb);
            //返回转换后的字符   
            return utf8.GetString(gb);
        }
        public static string utf8_gb2312(string text)
        {
            //声明字符集   
            Encoding utf8, gb2312;
            //utf8   
            utf8 =Encoding.GetEncoding("utf-8");
            //gb2312   
            gb2312 = Encoding.GetEncoding("gb2312");
            byte[] utf;
            utf = utf8.GetBytes(text);
            utf = Encoding.Convert(utf8, gb2312, utf);
            //返回转换后的字符   
            return gb2312.GetString(utf);
        }

        private void img_LoadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            tb_output.Text = "ok";
        }

        private void img_Click(object sender, EventArgs e)
        {
            getVCode();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (userIndex < userList.Count - 1) userIndex++;
            else userIndex = 0;
            changeUser();
        }

        private void readUserList()
        {
            dt.Columns.Add("usn", typeof(string));
            dt.Columns.Add("pwd", typeof(string));
            dt.Columns.Add("use", typeof(string));
            dt.Columns.Add("del", typeof(string));
            if (File.Exists("user.json"))
            {
                string ul = File.ReadAllText("user.json");
                JArray obj = (JArray)JsonConvert.DeserializeObject(ul);
                foreach(JObject o in obj)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = o["usn"].ToString();
                    dr[1] = o["pwd"].ToString();
                    dr[2] = (o["use"].ToString()=="True"?true:false);
                    dr[3] = "删  除";
                    dt.Rows.Add(dr);
                }
            }
            dg_userlist.DataSource = dt;
        }
        private void writeUserList()
        {
            dt.Columns.RemoveAt(3);
            string JsonString = string.Empty;
            JsonString = JsonConvert.SerializeObject(dt);
            File.WriteAllText("user.json", JsonString);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            readUserList();
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            writeUserList();
        }
       
        private void dg_userlist_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                if (MessageBox.Show("确定要删除"+dt.Rows[e.RowIndex][e.ColumnIndex].ToString(), "删除前确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (e.RowIndex<dt.Rows.Count)dt.Rows.RemoveAt(e.RowIndex);
                    dg_userlist.DataSource = dt;
                }
            }
        }
    }
}
